package com.woniu.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.woniu.platform.entity.PlatformRoleMenu;
import com.woniu.platform.mapper.PlatformRoleMenuMapper;
import com.woniu.platform.service.PlatformRoleMenuService;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.MenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlatformRoleMenuServiceImpl implements PlatformRoleMenuService {
    @Autowired
    private PlatformRoleMenuMapper platformRoleMenuMapper;

    /**
     * 查询角色拥有的菜单id
     * @param rid
     * @return
     */
    @Override
    public HttpResult queryRoleMenuMap(Integer rid) {
       QueryWrapper queryWrapper = new QueryWrapper();
       queryWrapper.eq("rid", rid);
       List<PlatformRoleMenu> list = platformRoleMenuMapper.selectList(queryWrapper);
       List<Integer> ridList = list.stream().map(e -> e.getMid()).collect(Collectors.toList());
        return new HttpResult<>().ok(ridList);
    }

    /**
     * 修改角色菜单
     * @param menuTree
     * @return
     */
    @Transactional
    @Override
    public HttpResult savaMenu(MenuTree menuTree) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("rid", menuTree.getRid());
            platformRoleMenuMapper.delete(queryWrapper);
            if(CollectionUtils.isNotEmpty(menuTree.getMenus())) {
                platformRoleMenuMapper.insertRoleMenu(menuTree);
            }
            return new HttpResult<>().ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
